package com.cgt.xiaotao.auth.controller;

import com.cgt.common.domain.dto.LoginFormDTO;
import com.cgt.common.utils.R;
import com.cgt.common.utils.WebUtils;
import com.cgt.xiaotao.auth.constants.JwtConstants;
import com.cgt.xiaotao.auth.service.IAccountService;
import com.cgt.xiaotao.model.exceptions.BadRequestException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 账户登录相关接口
 */
@Slf4j
@RestController
@RequestMapping("/accounts")
@Api(tags = "账户管理")
@RequiredArgsConstructor
public class AccountController {
    private final IAccountService accountService;


    @ApiOperation("登录并获取token")
    @PostMapping(value = "/login")
    public R<String> loginByPw(@RequestBody LoginFormDTO loginFormDTO) {
        return R.ok(accountService.login(loginFormDTO, false));
    }

    @ApiOperation("管理端登录并获取token")
    @PostMapping(value = "/admin/login")
    public R<String> adminLoginByPw(@RequestBody LoginFormDTO loginFormDTO) {
        return R.ok(accountService.login(loginFormDTO, true));
    }

    @ApiOperation("退出登录")
    @PostMapping(value = "/logout")
    public R<Void> logout() {
        try {
            accountService.logout();
            return R.ok();
        } catch (Exception e) {
            log.error("退出登录失败", e);
            return R.fail("退出登录失败");
        }
    }

    @ApiOperation("刷新token")
    @GetMapping(value = "/refresh")
    public R<String> refreshToken(
            @CookieValue(value = JwtConstants.REFRESH_HEADER, required = false) String userToken,
            @CookieValue(value = JwtConstants.ADMIN_REFRESH_HEADER, required = false) String adminToken,
            @RequestHeader(value = "Authorization", required = false) String authHeader
    ) {
        String refreshToken = null;

        // 首先尝试从cookie获取refresh token
        if (userToken != null) {
            refreshToken = WebUtils.cookieBuilder().decode(userToken);
        } else if (adminToken != null) {
            refreshToken = WebUtils.cookieBuilder().decode(adminToken);
        }
        // 如果cookie中没有，则从Authorization头获取（前端可能这样传递）
        else if (authHeader != null && authHeader.startsWith("Bearer ")) {
            refreshToken = authHeader.substring(7); // 去掉"Bearer "前缀
        } else if (authHeader != null) {
            refreshToken = authHeader; // 直接使用Authorization头的值
        }

        if (refreshToken == null || refreshToken.isEmpty()) {
            return R.fail("登录超时，请重新登录");
        }

        try {
            String newToken = accountService.refreshToken(refreshToken);
            return R.ok(newToken);
        } catch (Exception e) {
            log.error("刷新token失败", e);
            return R.fail("登录超时，请重新登录");
        }
    }
}
